/**
 * Created by zhaolei on 15/4/29. 
 */

'use strict';

var Client = require('./pop3lib').Client;
var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var retry = require('retry');

/**
 * 模块操作
 * @type {Function}
 */
var Fetcher = module.exports = function(options){
  this.options = _.assign(options,{port: 995,tls:true,mailparser:true});
  this.client = new Client(this.options);
  this.mails = [];
  this.list = {};
};

/**
 * 获取指定条目的邮件
 * @param  {String}   date 日期，如2015-01-01 搜索会判断大于此日期的邮件
 * @param  {Number}   offset 偏移量
 * @param  {Number}   limit   获取的数量
 * @param  {Function} cb   回调函数
 * @return {Array}         返回符合条件的邮件
 */
Fetcher.prototype.getContent = function(date,offset,limit,cb){
  
  //分页参数
  if(typeof offset !== Number){
    offset = parseInt(offset);
  }

  if(typeof offset !== Number){
    limit = parseInt(limit);
  }

  limit += offset;

  //date必须是一个字符串
  if(typeof date === 'function'){
    cb = date;
    return cb(new Error('Date must be String'));
  }

  //日期字符串不能为空
  if (_.isEmpty(date)) {
    return cb(new Error('Date must be not Empty'));
  }

  //匹配日期格式
  if(!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/i.test(date)){
    return cb(new Error('Date Fortmat be "YYYY-MM-DD"'));
  }

  var self = this;
  var operation = retry.operation({
    retries: 10,
    factor: 3,
    minTimeout: 1000,
    maxTimeout: 6000,
    randomize: true
  });

  if(!this.client.connected){
    self.client.connect(function(err){
      if(err && operation.retry(err)){
        if(err) {
          self.client.quit();
          return cb(err);
        }
      }
    });
  }

  async.waterfall([
    function(done){
      if(!_.size(self.list)){
        self.client.list(function(err,list){
          if(err) {
            self.client.quit();
            return cb(err);
          }

          //空邮箱
          if(_.size(list) == 0){
            self.client.quit();
            return cb(null,[]);
          }

          self.list = list;

          var tmp_count = _.keys(self.list);
          tmp_count.sort(function(a,b){return parseInt(a) > parseInt(b) ? -1 : 1});
          tmp_count = tmp_count.slice(offset,limit);
          done(null,_.chunk(tmp_count,10));
        });
      }else{
        var tmp_count = _.keys(self.list);
        tmp_count.sort(function(a,b){return parseInt(a) > parseInt(b) ? -1 : 1});
        tmp_count = tmp_count.slice(offset,limit);
        done(null,_.chunk(tmp_count,10));
      }

    },function(count,done){
      var stop = false;
      async.mapLimit(count,10,function(item,callback){
        var tmp = [];
        if(stop){
          return callback(null,tmp);
        }else{
          self.client.retrieve(item,function(err,res){
            if(err) {
              self.client.quit();
              return cb(err);
            }
            if(res === undefined){
              return callback(null,tmp);
            }else{
              tmp = [];
              if(res.length > 0){
                for(var i = 0;i<res.length;i++){
                  if(typeof res[i] == 'object' && moment(res[i].date).format('YYYY-MM-DD') >= date){
                    tmp.push(res[i]);
                  }else{
                    stop = true;
                  }
                }
              }
              callback(null,tmp);
            }
          });
        }
      },function(err,results){
        if(err) {
          self.client.quit();
          return cb(err);
        }
        done(null, _.flattenDeep(results));
      });
    }],function(err,res){
      cb(err,res);
    }
  );
};
